'''
Created on Apr 6, 2012

@author: daoxuandung

This module handle CRUD for post
'''


import json
from web.base import BaseHandler
from entity.entity import Post, Event
from google.appengine.ext.ndb import model
from web import util
from web import urls
from web import base
import logging

class CreateHandler(BaseHandler):
    """
    Create new post and save to datastore
    """
    @base.user_required
    def post(self):
        post = Post()
        post.author = util.get_current_user_key()
        post.post = self.request.params.get('post')
        event_id = self.request.params.get('event_id')
        post.event = model.Key(Event, int(event_id))
        post.put()
        self.response.write(json.dumps(util.ndb_to_dict(post)))

class ReadHandler(BaseHandler):
    """
    Return json object of post
    """
    def get(self):
        post_id = self.request.params.get('id')
        post = Post.get_by_id(post_id)
        if post:
            self.response.write(util.ndb_to_dict(post))
    
class ReadListHandler(BaseHandler):
    def post(self):     
        size = int(self.request.params.get('limit'))
        postList = Post.query().fetch_async(limit=size)
        postList = postList.get_result()
        returnList = []
        if postList is not None and len(postList) > 0:
            for e in postList:
                returnList.append(util.ndb_to_dict(e))
            
        # Return the id back to client
        if returnList:
            self.response.write(json.dumps(returnList))

class UpdateHandler(BaseHandler):
    """
    Update post.
    Only allow user to feature a post but not change the content
    """
    def post(self):
        post_id = self.request.params.get('id')
        star = self.request.params.get('star')
        if star:
            post = Post.get_by_id(post_id)
            if post:            
                post.star = star
                post.put_async()        
    

class DeleteHandler(BaseHandler):
    def post(self):
        post_id = self.request.params.get('id')
        post = Post.get_by_id(post_id)
        if post:
            post.delete_async()

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()